package com.monika.main.base;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.List;

/**
 * @Author whh
 * @Date: 2023/03/17/ 23:13
 * @description
 *
 * 使用spring上下文环境的后期处理接口加载外部的配置文件
 * 然后通过springboot的spi机制加载
 */
public class DiskPropertyLoadProcessor implements EnvironmentPostProcessor {

    public static final String DISK_PROPERTY = "/primal.properties";

    private final PropertySourceLoader propertyLoader = new PropertiesPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

//        new UrlResource()
        Resource resource = new FileSystemResource(DISK_PROPERTY);
        if(!resource.exists()){
            return;
        }

        try {
            List<PropertySource<?>> load = propertyLoader.load(resource.getFilename(), resource);
            for (PropertySource<?> e : load) {
                environment.getPropertySources().addFirst(e);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
